﻿using QWManage.DAL;
using QWManage.Logs;
using QWManage.Model;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BlackList.YiYeSync
{
    public class YiYeSyncMgr
    {
        private static int toSeconds(string dateTimeStr)
        {
            DateTimeOffset dateTimeOffset =
                DateTimeOffset.ParseExact(dateTimeStr,
                "yyyy-MM-ddTHH:mm:ss.fffZ",
                CultureInfo.InvariantCulture);
            long unixTimestampInSeconds = (long)(dateTimeOffset.UtcDateTime - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
            return (int)unixTimestampInSeconds;
        }
        public static void Execute()
        {
            try
            {
                LogMgr.Log("一叶匹配", "开始匹配");
                UserDAL userDAL = new UserDAL();
                RecordsDAL recordsDAL = new RecordsDAL();
                CustomerDAL customerDAL = new CustomerDAL();

                //1、从Record表中获取所有QWID为Null的记录
                var records = recordsDAL.GetRecordInfosQWIDNull();
                //2、遍历
                foreach (var record in records)
                {
                    //3、根据Record表中的字段WechatAppletUserid去表QW_Users找到对应用户记录
                    var userInfo = userDAL.GetUserInfoByYiYeUserId(record.WechatAppletUserid);
                    if (userInfo == null) continue;
                    //4、将根据Record表中的字段CreatedAt文本时间转换成时间戳 秒级别
                    int seconds = toSeconds(record.CreatedAt);
                    //5、在客户表QW_Customers中，
                    //根据F_UserID和F_CreateTime两字段来查询
                    //seconds 前减2秒，后加2秒，正好为5秒时间间隔
                    var customers = customerDAL.Search(userInfo.UserID, seconds - 2, seconds + 2);
                    if (customers.Count == 0) continue;
                    if (customers.Count == 1)
                    {
                        //若仅找到一条记录，就算直接匹配上，然后更新Records表中的QWID字段
                        recordsDAL.UpdateQWID(record.ID, customers[0].Exuserid);
                    }
                    else
                    {
                        //若找到多条记录，将客户的F_UserName与用户的Name比较，如果相同就算匹配成功，
                        //然后更新Records表中的QWID字段
                        foreach (var customer in customers)
                        {
                            if (customer.F_UserName == userInfo.Name)
                            {
                                recordsDAL.UpdateQWID(record.ID, customer.Exuserid);
                            }
                        }
                    }
                }
                LogMgr.Log("一叶匹配", "完成匹配");
            }
            catch (Exception ex)
            {
                LogMgr.Log("一叶匹配", ex.Message + "\t" + ex.ToString());
            }
        }
    }
}
